package com.malty.utils.spring;


import cn.hutool.core.util.ObjectUtil;
import com.sun.istack.internal.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author maltyshane
 * Spring 上下文获取工具
 */
@Component
public final class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 通过名称获取对象
     *
     * @param beanName
     * @return Object
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    /**
     * 通过类型获取对象
     *
     * @param beanClass
     * @return requiredType
     */
    public static <T> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }

    /**
     * 查看bean是否存在
     *
     * @param name
     * @return boolean
     */
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    /**
     * 判断bean是一个singleton
     *
     * @param name
     * @return boolean
     */
    public static boolean isSingleton(String name) {
        return applicationContext.isSingleton(name);
    }

    /**
     * 通过名称获取bean对象的类型
     *
     * @param name
     * @return Class
     */
    public static Class<?> getType(String name) {
        return applicationContext.getType(name);
    }

    /**
     * 获取当前的环境配置，如果无配置，则返回null
     *
     * @return 当前的环境配置
     */
    public static String[] getActiveProfiles() {
        return applicationContext.getEnvironment().getActiveProfiles();
    }

    /**
     * 获取当前的环境配置，当有多个环境配置时，只获取第一个
     *
     * @return 当前的环境配置
     */
    public static String getActiveProfile() {
        final String[] activeProfiles = getActiveProfiles();
        return ObjectUtil.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;
    }

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) {
        SpringUtils.applicationContext = applicationContext;
    }
}

